package com.mfs.common.response;


import com.mfs.common.enums.ResponseCodeEnum;

import java.lang.reflect.Method;

/**
 * 响应工具类
 * @author mfs
 * @date 20240405
 * */
public class ResponseUtil {
    public static <T> T createResponse(ResponseCodeEnum responseCodeEnum, Class<T> tClass) {
        return createResponse(responseCodeEnum.getCode(), responseCodeEnum.getMsg(), tClass);
    }

    public static <T> T createResponse(ResponseCodeEnum responseCodeEnum, String errorInfo, Class<T> tClass) {
        return createResponse(responseCodeEnum.getCode(), errorInfo, tClass);
    }

    public static <T> T createResponse(int errorNo, String errorInfo, Class<T> tClass) {
        try {
            BaseResponse response = (BaseResponse) tClass.newInstance();
            response.setErrorNo(errorNo);
            response.setErrorInfo(errorInfo);
            return (T) response;
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T createResponse(BaseResponse response, Class<T> tClass) {
        try {
            BaseResponse targetResponse = (BaseResponse) tClass.newInstance();
            if (response == null) {
                return createResponse(ResponseCodeEnum.FATAL.getCode(), "无返回值", tClass);
            }
            targetResponse.setErrorNo(response.getErrorNo());
            targetResponse.setErrorInfo(response.getErrorInfo());
            return (T) targetResponse;
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    public static BaseResponse createResponse(int errorNo, String errorInfo) {
        BaseResponse response = new BaseResponse();
        response.setErrorNo(errorNo);
        response.setErrorInfo(errorInfo);
        return response;
    }

    public static BaseResponse createResponse(ResponseCodeEnum responseCodeEnum) {
        return createResponse(responseCodeEnum.getCode(), responseCodeEnum.getMsg());
    }

    public static BaseResponse createResponse(ResponseCodeEnum responseCodeEnum, String errorInfo) {
        return createResponse(responseCodeEnum.getCode(), errorInfo);
    }
}
